<template>
  <view class="categorys">

    <up-status-bar></up-status-bar>

    <view style="width: 100%;" >
      <!-- 搜索框 -->
      <view class="input-view l_f_r_c_c">
        <view class="text_5_26">分类</view>
        <view class="input-view-box">
          <view class="input_viewbox">
            <uni-icons color="#ACACAC" type="search" size="20"></uni-icons>
            <input v-model="data.keywordList" @input="sherList" placeholder='请输入' />
          </view>
        </view>
        <image class="image" src="https://pili-vod.guanxikeji.com/fubao/img/1755250815689.png" @click="cat"></image>

      </view>
      <!-- 左右联动 -->
      <view class="category">
        <view class="nav">
          <scroll-view class="bg" scroll-y="true" :scroll-top="data.scrollTop" :scroll-with-animation="true"
                       :style="{height: data.screenWith + 'px'}">
            <block v-for="(item,index) in shoplist" :key="index">
              <view class="nav-item" :class="{'ac':data.active == index}"
                    @click="changeNav(index,item.ID)">
                <image class="nav_it_img" v-if="data.active == index" src="https://img.fubaozx.cn/static/newImg/categoryImg.png"></image>
                <text class="text">{{item.name}}</text>
              </view>
            </block>
          </scroll-view>
        </view>
        <view class="goodsBox" v-if="shoplist[data.active]&&shoplist[data.active].arr || data.active == 0">
          <!-- <view>
            <image src="https://pili-vod.guanxikeji.com/houdejia/img/1710467040708.png"
              style="width: 100%;height: 80px;"></image>
          </view> -->
          <view class="second">
            <scroll-view scroll-x="true" style="white-space: nowrap;">
              <text class="back text_4_24" v-for="(min,indexs) in shoplist[data.active]&&shoplist[data.active].arr" :key="indexs"
                    @click="second(min.ID)" :class="data.secondID==min.ID?'linbei':''">{{min.name}}</text>
            </scroll-view>
          </view>
          <view>
            <view class="emipt">
              <view class="sort_b">
                <view class="screenItem" @click="setSort(0)">
                  综合
                  <!-- <screen :type="data.sort == 1 ? 1 : data.sort == 2 ? 2 : 0"></screen> -->
                </view>
                <view class="screenItem" @click="setSort(1)">
                  销量
                  <screen :type="data.sort == 1 ? 1 : data.sort == 2 ? 2 : 0"></screen>
                </view>
                <view class="screenItem" @click="setSort(2)">
                  价格
                  <screen :type="data.sort == 3 ? 1 : data.sort == 4 ? 2 : 0"></screen>
                </view>

              </view>
            </view>
            <scroll-view scroll-y="true" :style="{height: data.screenWith + 'px'}"
                         >
              <empty v-if="data.shopsecond.length==0"></empty>
              <BJL-waterfall scrollHeight="50%" :data="data.shopsecond"
                             styleData="{backgroundColor: '#e7e7e7'}" @scrolltolowerFN='scrolltolower'>
                <template #scrollItem="{ item , index }">
                  <view class="item l_f_r">
                    <view class="ductarow ">
                      <image class="" :src="item.img" mode="aspectFill"
                             @click.stop="$goURl(`/pages/commodity/details?id=${item.ID}`)">
                      </image>
                    </view>
                    <view class="right flex_1">
                      <view class="ductbrow text_b_28 textsl2"
                            @click.stop="$goURl(`/pages/commodity/details?id=${item.ID}`)">
                        {{item.name}}
                      </view>
                      <view class="text_c_8f text_5_20">已售{{item.virtually_sales+item.sales}}</view>
                      <view class="lsjf text_c_r text_5_20" v-if="item.discount>0">
                        送{{getDiscountJf(item)}}资产积分
                      </view>
                      <view class="ductdrow box_db l_f_r_sb_c">
                        <view class="ductdrowa"
                              @click.stop="$goURl(`/pages/commodity/details?id=${item.ID}`)">
                          ￥{{$toFiexd(item.price)}}
                        </view>
                        <view class="ductdrowb l_f_r_c_c" @click="bindChange(item,index,1)">
                          <image src="https://img.fubaozx.cn/static/newImg/categoryImg2.png" class="addImg"></image>
                        </view>
                      </view>
                    </view>
                  </view>
                </template>
                <template #bottom>
                  <view style="width: 100%;height: 80rpx;margin-bottom: 0px;"></view>
                </template>
              </BJL-waterfall>

            </scroll-view>
          </view>
        </view>
      </view>

    </view>
    <!-- 立即购买弹窗 -->
    <uni-popup ref="popup">
      <view class="popup-content">
        <view class="top">
          <uni-icons type="closeempty" size="22" @click="close"></uni-icons>
        </view>
        <view class="goodsdetail">
          <view class="goodsimg">
            <image :src="data.goods.img?data.goods.img:data.goodsdetali.img" mode="aspectFill"></image>
          </view>
          <view class="right">
            <view class="title textsl2">
              {{ data.goods.name }}
            </view>
            <view class="price">
              {{data.goods.price}}
            </view>
            <view class="stock">
              库存：{{data.goods.stock}}
            </view>
          </view>
        </view>
        <view class="numbox">
          <view class="">
            数量
          </view>
          <uni-number-box v-model="data.number" />
        </view>
        <view class="">
          <view class="specsbox" v-for="(item,index) in data.lists" :key="index">
            <view class="title">
              {{item.attr}}
            </view>
            <view class="specslist">
              <view v-for="(items,indexs) in item.val" @click="ckeck(index,indexs)" :key="indexs">
                <text class="specsitem"
                      :class="{actives:data.listckeck[index]==indexs}">{{items}}</text>
              </view>
            </view>
          </view>

        </view>
        <view class="buy" @click="shoppingCart">
          加入购物车
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import screen from "@/components/screen/screen.vue"
import {
  ref,
  reactive,
  getCurrentInstance
} from "vue";
import {
  onLoad,
  onShow,
  onReachBottom
} from "@dcloudio/uni-app";
const {
  appContext
} = getCurrentInstance();
const data = reactive({
  active: 0,
  scrollTop: 0,
  height: 0,
  shoplist: [],
  // 分类列表子集
  shoplistDe: [],
  shopsecond: [],
  secondID: -1,
  dataID: 1,
  isShow: false, //是否显示规格蒙版
  goods: {},
  lists: [], //规格
  goodsdetali: {},
  listckeck: [],
  listckecks: [],
  selectlist: [],
  speci: 0, //规格ID
  number: 1, //数量
  page: 0,
  pages: 1,
  size: 10,
  screenWith: '', //屏幕高度
  keywordList: '', //搜索信息
  sort: 2, //排序
})
let shoplist = ref([])
const popup = ref()
function getDiscountJf(item) {
  if (item.discount > 0) {
    return ((Number(item.price)  * Number(item.discount/ 100) )).toFixed(4)
  } else {
    return 0
  }

}
onLoad((opt) => {
  // data.shoplistDe = data.shoplist[0].child
  secondary()
})
onShow(() => {
  // 业务逻辑
  uni.getSystemInfo({
    success: function(res) {
      console.log(res);
      if (res.platform == 'ios') {
        if (res.windowBottom > 0) {
          data.screenWith = res.windowHeight - 94
        } else {
          data.screenWith = res.windowHeight - 144
        }
      } else {
        if (res.windowBottom > 0) {
          data.screenWith = res.windowHeight - 80
        } else {
          data.screenWith = res.windowHeight - 130
        }
      }
    }
  });
})
const scrolltolower = () => {
  getdatas()
}
const buttonClick = (e) => {
  popup.value.open('bottom')
}
// 点击加入购物车
function create() {

}
const ckeck = (a, b) => { //规格选择
  console.log("选择完成", data.listckeck)
  data.listckeck[a] = b
  // console.log("选择完成", data.listckeck,data.lists)
  let num = data.listckeck.filter(item => {
    return item >= 0
  }).length

  if (num == data.lists.length) {
    let attribute = ''
    data.listckeck.forEach((item, index) => {
      if (index < data.lists.length) {
        attribute = attribute + data.lists[index].id[item] + (index < data.lists.length - 1 ? '|' :
            '')
      }
    })
    let listsss = []
    data.lists.forEach((item, index) => {
      listsss.push(item.ID[data.listckeck[index]])
    })
    data.speci = listsss[0]
    data.listckecks = listsss
    data.attribute = attribute
    let goodsNmae = data.goods.name
    data.goods = data.goodsdetali.attribute_list.filter(item => {
      return item.attribute == attribute
    }).map(item => {

      // data.speci = item.attr[0].ID
      return {
        img: item.img,
        coupon: item.coupon,
        price: item.price,
        stock: item.stock,
        ID: item.ID,
        name: goodsNmae
      }
    })[0]

  }
}
// 关闭弹窗
const close = () => {
  popup.value.close()
}

function goURl() {
  uni.navigateBack()
}
//排序
function setSort(index) {
  if (index == 0 && data.sort != 0) {
    data.sort = index
  } else if (index == 1 && (data.sort < 1 || data.sort > 2)) {
    data.sort = 1
  } else if (index == 1) {
    if (data.sort == 1) {
      data.sort = 2
    } else {
      data.sort = 1
    }
  } else if (index == 2 && (data.sort < 3)) {
    data.sort = 3
  } else if (index == 2) {
    if (data.sort == 3) {
      data.sort = 4
    } else {
      data.sort = 3
    }
  }
  sherList()
}
// 点击加入购物车图片
function bindChange(item, index, e) {
  data.listckeck = [0]
  appContext.config.globalProperties.$request({
    url: `api/goods_list_all/0/`,
    method: 'POST',
    data: {
      id: item.ID
    },
    success: (res) => {
      if (res.errno == 0) {
        data.speci = res.data.attribute_list[0].ID
        if (res.data.attribute_list.length != 1) {
          popup.value.open('bottom')
          data.number = 1

        } else {
          data.number = 1
          shoppingCart(res.data.attribute_list[0].ID)
        }
        data.lists = arr(res.data.attribute_list)
        console.log(data.lists, "data.lists")
        data.goodsdetali = res.data
        data.goods = {
          img: res.data.img,
          price: res.data.price,
          stock: res.data.stock,
          coupon: res.data.coupon,
          ID: res.data.attribute_list[0].ID,
          name: res.data.name,
        }
      }
    }
  })
}
// 规格排列组合
const arr = (arr) => {
  var list = []
  arr[0]['attr'].forEach(f => {
    // console.log()
    list.push({
      attr: f.attr,
      val: [],
      id: [],
      ID: []
    })
    // data.listckeck.push(0)
  })
  arr.forEach(f => {
    f.attr.forEach(t => {
      for (var k = 0; k < list.length; k++) {
        if (list[k].attr == t.attr) {
          list[k].val.push(t.val)
          list[k].id.push(t.ID)
          list[k].ID.push(f.ID)
        }
      }
    })
  })
  for (var i = 0; i < list.length; i++) {
    list[i].val = [...new Set(list[i].val)]
    var s = []
    for (var k = 0; k < list[i].val.length; k++) {
      s.push(k == 0 ? 1 : 0)
    }
    data.selectlist.push(s)
  }
  list.forEach(item => {
    item.id = Array.from(new Set(item.id))
  })
  return list
}

function shoppingCart(id) {
  let imd = ''
  if (typeof(id) != 'object') {
    imd = id
  } else {
    imd = data.speci
  }
  appContext.config.globalProperties.$request({
    url: `api/shoppingCart/`,
    method: 'POST',
    data: {
      attribute_id: imd,
      number: data.number
    },
    success: (res) => {
      if (res.errno == 0) {
        uni.showToast({
          icon: 'none',
          title: '加入购物车成功'
        })
        popup.value.close()
      } else {
        uni.showToast({
          icon: 'none',
          title: res.errmsg
        })
      }

    }
  })
}
// 搜索
function sherList(e) {
  data.page = 0
  data.pages = 1
  data.shopsecond = []
  getdatas()
}
// 点击搜索
function shoer() {
  data.page = 0
  data.pages = 1
  data.shopsecond = []
  data.secondID = -1
  getdatas()
}
// 点击二级分类
function second(id) {
  data.page = 0
  data.pages = 1
  data.shopsecond = []
  data.secondID = id
  getdatas()
}
// 获取数据
function getdatas() {
  if (data.page < data.pages) {
    data.page++
    let datas = []
    appContext.config.globalProperties.$request({
      url: `api/goods_list_all/${data.dataID}/?class_second_id=${data.secondID}&page=${data.page}&size=${data.size}&keyword=${data.keywordList}&sort=${data.sort}&is_single=0`,
      method: 'GET',
      success: (res) => {
        datas = res.data.data
        console.log("res", res)
        if (res.errno == 0) {
          data.shopsecond = [...data.shopsecond, ...datas]
          data.pages = Math.ceil(res.data.total / data.size)
        } else {
          uni.showToast({
            icon: 'none',
            title: res.errmsg
          })
          data.shopsecond = []

        }
        console.log("data.shopsecond", data.shopsecond)
      }
    })
  }
}
// 商品分类
function secondary() {
  appContext.config.globalProperties.$request({
    url: `api/typeList/`,
    method: 'GET',
    success: (res) => {
      if (res.errno == 0) {
        data.dataID = 0
        let datae = res.data.class_first
        let datas = res.data.class_second

        shoplist.value = []
        datae.forEach((item, index) => {
          shoplist.value.push({
            name: item.name,
            ID: item.ID,
            arr: [{
              name: '全部',
              ID: -1,
            }],
          })

          datas.forEach((items, indexs) => {
            if (item.ID == items.class_first_id) {
              shoplist.value[index].arr.push({
                name: items.name,
                ID: items.ID,
              })
            }
          })
        })
        getdatas()
        shoplist.value.unshift({
          name: '全部',
          ID: 0,
        })
      }

    }
  })
}

function changeNav(index, id) {
  data.secondID = -1
  data.page = 0
  data.pages = 1
  data.shopsecond = []
  data.dataID = id
  data.active = index;
  data.scrollTop = data.height * (index - 2);
  // if (data.screenWith > 624) {
  //   data.screenWith = data.screenWith - 44
  // }
  getdatas(0, 0)
  // 在这里请求接口 展示右侧商品数据
  // data.shoplistDe = data.shoplist[index].child
}

function cat() {
  uni.navigateTo({
    url: '/pages/cat/cat' // 需要跳转的tab页面路径
  });

}
</script>

<style scoped lang="scss">
$nav-height: 30px;
$paddings: 10px;

page {
  background-color: #F8F8F8;
}

.categorys {
  height: calc(100vh - 50px);
}

.input-view {
  flex-direction: row;
  flex: 1;
  background-color: #fff;
  flex-wrap: nowrap;
  padding: $padding;
  overflow: hidden;
  padding-bottom: 20rpx;


  .image {
    width: 36rpx;
    height: 36rpx;
  }

  .cate {
    width: 15%;
    display: flex;
    align-items: center;
    flex-direction: column;


  }

  .input-view-box {
    margin: 0 20rpx;

    .input_viewbox {
      background: #FFFFFF;
      display: flex;
      // justify-content: space-between;
      align-items: center;
      width: 558rpx;
      height: 64rpx;
      border-radius: 62rpx 62rpx 62rpx 62rpx;
      border: 1rpx solid #D5D5D5;
      .uni-icons {
        margin: 0 20rpx;
      }
    }

    uni-input {
      height: 38px;
      line-height: 72upx;
      width: 80%;
      font-size: 16px;
      color: #9f9f9f;
    }

    .btn {
      width: 120rpx;
      height: 100%;
      background: $green;
      border-radius: 40rpx 40rpx 40rpx 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: bold;
      font-size: 28rpx;
      color: #FFFFFF;
    }
  }

}

.category {
  display: flex;
  margin-top: 24rpx;
  // position: absolute;
  width: 100%;
  // height: calc(100% - var(--status-bar-height));

  /* 隐藏滚动条样式 */
  ::-webkit-scrollbar {
    width: 0;
    height: 0;
  }

  uni-scroll-view {
    height: 100%;
  }

  .bg {
    background: #f8f8f8;
  }

  .nav {
    width: 24%;
    max-height: 95vh;

    .nav-item {
      width: inherit;
      text-align: center;
      height: 60px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;


      .text {
        font-size: 26rpx;
        color: #000000;
        font-weight: 500;
        white-space: normal;
        word-wrap: break-word;
        line-height: 40rpx;
        padding: 0 8px;
      }
      .nav_it_img{
        width: 6rpx;
        height: 40rpx;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .ac {
      color: #2D2D2D;
      font-size: 26rpx;
      background: #fff;
      font-weight: 500;
      // padding: 0 8px;
      //border-radius: 32rpx 0rpx 0rpx 32rpx;
      .text{
        color: #FF4A01;
      }
    }

  }

  .goodsBox {
    width: 77%;

    background: #ffffff;
    border-radius: 8rpx;

    .second {
      width: calc(100% - 30rpx);
      display: flex;
      margin-left: 30rpx;

      .back {
        display: inline-block;
        padding: 4px 12px;
        margin-right: 10px;
        margin-top: 17px;
        border-radius: 60rpx 60rpx 60rpx 60rpx;
        //border: 1rpx solid #D9D9D9;
        background-color: #F6F6F6;
        font-weight: 400;
        font-size: 26rpx;
      }

      .linbei {
        color: #FF4A01;
        background: #FFF0EA;
        border-radius: 60rpx 60rpx 60rpx 60rpx;
        border: 2rpx solid #FF4A01;
      }
    }

    .goods {
      display: flex;
      flex-wrap: wrap;

      // padding: 30rpx 0;
      // height: 500px;
      .goods-item {
        width: 100%;
        margin-bottom: 40rpx;
        margin-right: 20rpx;

        .commImg {
          display: block;
          width: 246rpx;
          height: 246rpx;
          border-radius: 10rpx;
        }

        .commodList {
          width: 65%;
          margin-left: 20upx;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .name {
            color: #303133;
            font-size: 14px;
            font-weight: 700;
            overflow: hidden; //超出的文本隐藏
            display: -webkit-box;
            -webkit-line-clamp: 2; // 设置从第几行后开始省略
            -webkit-box-orient: vertical;
          }

          .namel {
            color: #909399;
            font-size: 14px;
            font-weight: 400;
            overflow: hidden; //超出的文本隐藏
            display: -webkit-box;
            -webkit-line-clamp: 2; // 设置从第几行后开始省略
            -webkit-box-orient: vertical;
          }

          .price {
            display: flex;
            align-items: center;

            text {
              color: $color1;
            }

            image {
              width: 30px;
              height: 14px;
              margin-left: 10upx;
            }
          }

          .preferential {
            display: flex;
            align-items: center;
            justify-content: flex-end;

            text {
              color: #909399;
              font-size: 10px;
            }

            image {
              width: 25px;
              height: 25px;
              margin-right: 10px;
            }
          }
        }

      }
    }
  }
}

.emipt {
  height: 38rpx;
  width: 100%;
  padding-bottom: 20rpx;
}

::v-deep .scroll-view_H {
  width: 100% !important;
}

// .productbox {
// 	display: flex;
// 	flex-wrap: wrap;
// 	justify-content: space-between;

// .list {
// 	width: 46%;
// 	padding-bottom: 16rpx;
// 	background: #FFFFFF;
// 	box-shadow: 0rpx 2rpx 12rpx 2rpx rgba(0, 0, 0, 0.06);
// 	border-radius: 24rpx 24rpx 24rpx 24rpx;
// 	margin: 12rpx 0rpx;
// 	padding: 10rpx;
// }


.item {

  padding: 26rpx 16rpx;
  box-sizing: border-box;
  margin: 12rpx 0rpx;
  width: 524rpx;

  .ductarow {
    margin-right: 16rpx;
    image {
      width: 168rpx;
      height: 168rpx;
    }
  }
  .right{
    overflow: hidden;
  }

  .ductbrow {
    word-wrap: break-word;
    color: #2D2D2D;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    width: 100%;
  }

  .ductcrow {
    font-weight: 400;
    font-size: 20rpx;
    color: #7AA048;
  }
  .text_c_8f{
    margin:10rpx 0
  }

  .box_db {
    padding: 10rpx;
  }

  .ductdrow {
    .ductdrowa {
      font-weight: bold;
      font-size: 30rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #F63B29;
    }

    .ductdrowb {

      .addImg {
        width: 36rpx;
        height: 36rpx;
      }
    }
  }
  .lsjf {
    height: 36rpx;
    padding: 0 10rpx;
    margin: 5rpx 0;
    width: fit-content;
    background: #FFF5E5;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    color: #C56530;
  }
}

.food-cl {
  width: 100%;
  text-align: center;
  color: #dbdbdb;
  padding: 15rpx 0 30rpx 0;
}

// }

// #ifdef APP-PLUS
.popup-content {
  margin-bottom: 0px !important
}

// #endif
//#ifdef MP-WEIXIN
.popup-content {
  margin-bottom: 0rpx !important;
  position: absolute;
  bottom: -34px;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
}

// #endif
.popup-content {
  background-color: #fff;
  padding: 30upx;
  border-radius: 30upx 30upx 0 0;
  margin-bottom: 50px;

  .top {
    display: flex;
    justify-content: flex-end;
  }

  .goodsdetail {
    display: flex;

    .goodsimg {
      width: 200upx;
      height: 200upx;
      margin-right: 20upx;

      image {
        width: 200upx;
        height: 200upx;
        // background-color: aqua;
        border-radius: 20upx;
      }
    }

    .right {
      .title {
        font-size: 34rpx;
        color: #000;
      }

      .price {
        color: red;
        font-size: 32upx;
        margin-top: 10rpx;
      }

      .stock {
        color: #999;
        font-size: 26 upx;
        margin: 20upx 0;
      }

      .specifications {
        font-size: 28upx;
      }
    }
  }

  .numbox {
    display: flex;
    justify-content: space-between;
    margin-top: 40upx;
  }

  .specsbox {
    margin-top: 40upx;

    .title {
      margin-bottom: 10upx;
    }

    .specslist {
      display: flex;
      flex-wrap: wrap;

      .specsitem {
        font-size: 28upx;
        padding: 5upx 20upx;
        border-radius: 10upx;
        border: 1upx solid #555;
        color: #555;
        margin-right: 20upx;
        margin-top: 20upx;
      }

      .actives {
        background-color: rgba(0, 195, 86, 0.1);
        border: 1upx solid #F63B29;
        color: #F63B29;
        border-radius: 10rpx;
      }
    }
  }

  .buy {
    background-color: #F63B29;
    color: #fff;
    padding: 20upx;
    text-align: center;
    border-radius: 40upx;
    margin-top: 40upx;

  }
}

.sort_b {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 30rpx;
  font-weight: 500;
  font-size: 26rpx;
  color: #122950;

  .screenItem {
    display: flex;
    align-items: center;

    .saixuan {
      width: 34rpx;
      height: 34rpx;
    }
  }
}

.sort {
  padding: 30rpx;
  margin-top: 50rpx;

  .soat_a {
    font-weight: 500;
    font-size: 26rpx;
    color: #122950;

    .tit {
      font-weight: bold;
      color: 000;
    }

    .list {
      display: flex;
      flex-wrap: wrap;
      margin: 20rpx 0rpx;

      .itembox {
        padding: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 2rpx solid #666D7F;
        border-radius: 10rpx;
        margin: 5rpx;
      }
    }
  }
}
</style>
